package dasregistry.ontology.browsing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import org.biojava.bio.seq.io.ParseException;
import org.biojava.ontology.Ontology;
import org.biojava.ontology.Term;
import org.biojava.ontology.Triple;
import org.biojava.ontology.io.OboParser;

public class TraverseTowardsRoot {
	Ontology ontology;
	List<String> arcs;
	Set<Term> nodes;
 
	public TraverseTowardsRoot(String oboFileName, String ontoName,
			String ontoDescription, String root) throws ParseException,
			FileNotFoundException, IOException {
		
//		OboParser parser = new OboParser();
//		InputStream inStream = this.getClass().getResourceAsStream(
//				"/ontologies/" + oboFileName);
//		BufferedReader oboFile=new BufferedReader(new InputStreamReader(
//				inStream));
		OboParser parser = new OboParser();
		ontology = parser.parseOBO(new BufferedReader(new FileReader(oboFileName)), ontoName, ontoDescription);
		arcs = new Vector<String>();
		nodes = new HashSet<Term>();
		
		//FileWriter fstream = new FileWriter("/Users/jw12/graphout.dot");
        //BufferedWriter out = new BufferedWriter(fstream);
    
        //set up nodes and arcs
		traverse(ontology.getTerm(root));
		//out.write("digraph \n");
		//out.write(ontology.getName());
		//out.write(" {\n");
		for (Term t : nodes) {
			
			System.out.println(t.getName());
			System.out.println(" [label=\""
					+ t.getDescription() + "\"];");
		}
		for (String arc : arcs) {
			
			System.out.println(arc);
		}
		
	}
 
	
 
	private void traverse(Term subject) {
		Set<Triple> triples = ontology.getTriples(null, subject, null);
		String arc;
		for (Triple triple : triples) {
			System.out.println("name="+triple.getName()+"|");
			nodes.add(triple.getSubject());
			//System.out.println("subject:"+triple.getSubject());
			nodes.add(triple.getObject());
			//System.out.println("object:"+triple.getObject());
			//System.out.println(triple.toString());
			arc = triple.toString();//.replace(triple.getPredicate().getName(),"->");
			if (!arcs.contains(arc))
				arcs.add(arc);
			//System.out.println("traversing");
			traverse(triple.getSubject());
		}
	}
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			//"SO", "sequence ontology", "so.obo"
			new TraverseTowardsRoot("/Users/jw12/workspaceJune2009/dasregistry/resources/ontologies/biosapiens.obo", "BO", "description", "BS:00330");
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
}
